package leetcode.editor.day;

// 1464. 数组中两元素的最大乘积
// https://leetcode.cn/problems/maximum-product-of-two-elements-in-an-array/
class MaximumProductOfTwoElementsInAnArray {
    public static void main(String[] args) {
        Solution solution = new MaximumProductOfTwoElementsInAnArray().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        // 排序
    /*public int maxProduct(int[] nums) {
        Arrays.sort(nums);
        return (nums[nums.length - 1] - 1) * (nums[nums.length - 2] - 1);
    }*/

        // 一次遍历，寻找最大值和次大值
        // https://leetcode.cn/problems/maximum-product-of-two-elements-in-an-array/solution/shu-zu-zhong-liang-yuan-su-de-zui-da-che-oqkf/
        public int maxProduct(int[] nums) {
            int a = Math.max(nums[0], nums[1]), b = Math.min(nums[0], nums[1]);
            for (int i = 2; i < nums.length; i++) {
                if (nums[i] > a) {
                    b = a;
                    a = nums[i];
                } else if (nums[i] > b) {
                    b = nums[i];
                }
            }

            return (a - 1) * (b - 1);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
